<?php
namespace App\Service\Admin;

class CateService extends BaseService
{
    //分类

    /**
     * 列表
     * @param array $pages【start，limit】
     */
    public function getIndex($pages, $pas)
    {
        $start = ($pages['start'] - 1) * $pages['limit'];
        $db = $this->dbConn($this->dbCate)
            ->where('del', 0)
            ->where('type', $pas['type']);
        $total = $db->count();
        $res = $db->skip($start)->take($pages['limit'])
            ->orderBy('id', 'desc')
            ->get();
        if (!count($res)) {
            return $this->toback(-2, '没有记录');
        }
        $types = $this->cateTypes;
        $arys = [];
        foreach ($res as $v) {
            $v = (array) $v;
            $tname = array_key_exists($v['type'], $types) ? $types[$v['type']] : '';
            $arys[] = [
                'id' => $v['id'],
                'type' => $v['type'],
                'type_name' => $tname,
                'title' => $v['title'],
                'img' => $v['icon'],
                'price' => toNumber($v['price']),
                'uptime' => $v['uptime'],
            ];
        }
        return $this->toback(0, '', $arys, $total);
    }

    //添加
    public function add($pas)
    {
        $res = (array) $this->dbConn($this->dbCate)
            ->where('del', 0)
            ->where('type', $pas['type'])
            ->where('title', $pas['title'])
            ->first();
        if (!empty($res)) {
            return $this->toback(-2, '已存在同名分类');
        }
        $pas['uptime'] = $pas['addtime'] = toDate();
        $lastid = $this->dbConn($this->dbCate)->insertGetId($pas);
        if (!$lastid) {
            return $this->toback(-1, 'error');
        }
        return $this->toback();
    }

    //修改
    public function modify($id, $pas)
    {
        $res = $this->dbConn($this->dbCate)
            ->where('del', 0)
            ->where('id', $id)
            ->first();
        if (empty($res)) {
            return $this->toback(-2, '没有记录');
        }
        $pas['uptime'] = toDate();
        $up = $this->dbConn($this->dbCate)->where('id', $id)->update($pas);
        if (!$up) {
            return $this->toback(-1, 'error');
        }
        return $this->toback();
    }

    //删除
    public function del($id)
    {
        $res = $this->dbConn($this->dbCate)
            ->where('del', 0)
            ->where('id', $id)
            ->first();
        if (empty($res)) {
            return $this->toback(-2, '没有记录');
        }
        $up = $this->dbConn($this->dbCate)->where('id', $id)
            ->update(['del' => 1, 'deltime' => toDate()]);
        if (!$up) {
            return $this->toback(-1, 'error');
        }
        return $this->toback();
    }
}